package com.sample.videocollection;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.webkit.URLUtil;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.sample.videocollection.adapter.BaseBindingAdapter;
import com.sample.videocollection.adapter.BindingViewHolder;
import com.sample.videocollection.adapter.OnItemClickListener;
import com.sample.videocollection.databinding.ActivityMainBinding;
import com.sample.videocollection.entity.DBWebEntity;
import com.sample.videocollection.entity.MyObjectBox;
import com.sample.videocollection.entity.WebEntity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import io.objectbox.Box;
import io.objectbox.BoxStore;
import io.objectbox.android.AndroidObjectBrowser;

public class MainActivity extends AppCompatActivity {

    ActivityMainBinding mBinding;
    private MyAdapter mAdapter;
    private Box<DBWebEntity> mBox;//数据库数据列表


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mBinding = DataBindingUtil.setContentView(this,R.layout.activity_main);

        initView();
        initData();

    }

    private void initView() {
        //获取表DBWebEntity中的数据，类似于列表，但不是列表
        mBox = ObjectBox.get().boxFor(DBWebEntity.class);

        //初始化recyclerView
        LinearLayoutManager layout = new LinearLayoutManager(this);
        mBinding.rvVideo.setLayoutManager(layout);
        DividerItemDecoration decor = new DividerItemDecoration(this, layout.getOrientation());
        mBinding.rvVideo.addItemDecoration(decor);
        mAdapter = new MyAdapter(this);
        mBinding.rvVideo.setAdapter(mAdapter);


    }

    /**
     * 处理数据
     */
    private void initData() {


        List<DBWebEntity> newList = new ArrayList<>();
        boolean isFirst = SPUtils.getInstance().getBoolean("isFirst");
        if (isFirst) {
            newList = mBox.getAll();
        }else {
            String jsonData = getJsonData("webs.json");
            List<WebEntity> list = JSONObject.parseArray(jsonData, WebEntity.class);
            newList = saveData(list);
            SPUtils.getInstance().put("isFirst",true);
        }

        mAdapter.setData(newList);
        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                DBWebEntity webEntity = mAdapter.getData().get(position);
                final String site = webEntity.getBaseUrl();
                boolean b = checkUriValid(site);
                if (b) {
                    openBroswer(site);
                }else {
                    ToastUtils.showShort("无效地址");
                }
            }

            @Override
            public void onItemLongClick(int position) {
                DBWebEntity object = mAdapter.getData().get(position);
                mAdapter.getData().remove(object);
                mAdapter.notifyItemRemoved(position);
                mBox.remove(object);
            }
        });
    }

    private List<DBWebEntity> saveData(List<WebEntity> list) {
        for (int i = 0; i < list.size(); i++) {
            WebEntity webEntity = list.get(i);
            DBWebEntity dbWebEntity = new DBWebEntity();
            dbWebEntity.setTitle(webEntity.getTitle());
            dbWebEntity.setBaseUrl(webEntity.getBaseUrl());
            dbWebEntity.setSearchUrl(webEntity.getSearchUrl());
            mBox.put(dbWebEntity);
        }
        return mBox.getAll();
    }


    /**
     * 打开浏览器
     * @param site 网址
     */
    private void openBroswer(String site) {
        Uri uri = Uri.parse(site);
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        intent.setData(uri);
        startActivity(intent);
    }

    /**
     * 检测网址是否有效
     * @param urlString 网址
     * @return 目前的情况来看所有的都是true，因为这个是正在表达式而不是探测功能
     */
    private boolean checkUriValid(String urlString) {
        try {
            URL url = new URL(urlString);
            return URLUtil.isValidUrl(urlString) && Patterns.WEB_URL.matcher(urlString).matches();
        } catch (MalformedURLException e) {

        }

        return false;
    }

    /**
     * 读取assets文件夹下的json文件
     * @return 返回json的字符串
     */
    private String getJsonData(String fileName) {
        StringBuilder stringBuilder = new StringBuilder();
        //获得assets资源管理器
        AssetManager assetManager = this.getAssets();
        //使用IO流读取json文件内容
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName), StandardCharsets.UTF_8));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();

    }

    /**
     * 列表适配器
     */
    class MyAdapter extends BaseBindingAdapter<DBWebEntity> {
        MyAdapter(Context context) {
            super(context);
        }

        @Override
        protected int getLayoutId(int viewType) {
            return R.layout.item_web;
        }

        @Override
        protected void onBindItem(@NonNull final BindingViewHolder holder, final int position) {
            ViewDataBinding binding = holder.getBinding();
            View root = binding.getRoot();
            TextView tv_title = root.findViewById(R.id.tv_title);
            TextView tv_site = root.findViewById(R.id.tv_site);
            DBWebEntity entity = getData().get(holder.getAdapterPosition());
            tv_title.setText(entity.getTitle());
            tv_site.setText(entity.getBaseUrl());
            root.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mOnItemClickListener != null) {
                        mOnItemClickListener.onItemClick(holder.getLayoutPosition());
                    }
                }
            });
            root.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    if (mOnItemClickListener != null) {
                        mOnItemClickListener.onItemLongClick(holder.getLayoutPosition());
                    }
                    return false;
                }
            });
        }
    }

}
